/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package examples;

import java.text.DecimalFormatSymbols;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.DocumentFilter;

/**
 *
 * @author nicolas
 */
public class CalcFilter extends DocumentFilter
{

  private DecimalFormatSymbols dfs = new DecimalFormatSymbols();
  private char decimalPoint;
  private char[] chars;

  // TODO internationnalisation du .
  // TODO précision du nombre
  // TODO integer
  public CalcFilter()
  {
    //decimalPoint = dfs.getDecimalSeparator();
    decimalPoint = '.';
    chars = new char[]
            {
              '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', decimalPoint
            };
  }

  @Override
  public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException
  {
    if (string != null)
    {
      replace(fb, offset, string.length(), string, attr);
    }
  }

  @Override
  public void replace(FilterBypass fb, int offset, int length, String string, AttributeSet attrs) throws BadLocationException
  {
    if (!verify(string) || !verifyDecimalPoint(fb, string))
    {
      return;
    }
    super.replace(fb, offset, length, string, attrs);
  }

  // TODO extraire
  private boolean verifyDecimalPoint(FilterBypass fb, String string) throws BadLocationException
  {
    if (string != null && string.equals("" + decimalPoint))
    {
      String s = fb.getDocument().getText(0, fb.getDocument().getLength());
      int i = s.indexOf(decimalPoint);
      System.out.println("indexOf(decimalPoint) : " + s + " is in " + i);
      if (i != -1)
      {
        return false;
      }
    }
    return true;
  }

  // TODO regex
  // TODO extraire
  private boolean verify(String s)
  {
    if (s == null || s.equals(""))
    {
      return true;
    }
    char[] sc = s.toCharArray();
    for (int i = 0, size = sc.length; i < size; i++)
    {
      for (int j = 0; j < chars.length; j++)
      {
        if (sc[i] == chars[j])
        {
          return true;
        }
      }
    }
    return false;
  }
}
